﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Net;
using System.Collections;
using System.Text;
using System.Xml;
using System.Reflection;


namespace ABC_SuperSign
{
    public partial class ABC_Super : Form
    {
        private string m_assetID ;//ID in the database tt
        //private string m_assetID = "5937";
        //private string[] m_local_images = null;
        private int m_selected = 0;
        private int m_selected_url = 0;
        private int m_begin = 0;
        private int m_end = 0;
        //private bool m_is_default = false;
        private bool m_download_ready = false;
        private ArrayList m_ArrayImage_url = new ArrayList();
        private ArrayList m_defaultArray_url = new ArrayList();
        private List<DateTime> m_schedules = new List<DateTime>();
        private int m_download_num = 5;
        private int m_num_pic = 0;
        //private string m_lastest_schedules;
        //url
        private Image[] m_images = null;
        private Image[] m_images_default = null;
       

        //test
        //static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
        //static int alarmCounter = 1;
        //static bool exitFlag = false;


        public ABC_Super()
        {
            InitializeComponent();
            //get initial picture from resource
            Assembly assem = this.GetType().Assembly;
            PB_display_pic.Image = (System.Drawing.Image)Properties.Resources._default;
            m_assetID = (String)Properties.Settings.Default.AssetID;
            DB_Start_Stop.Enabled = true;

            //Properties.Settings.

            Picture_Display_Timer.Enabled = false;
            //Access_DB_Timer.Enabled = true;
            Check_Schedule_Timer.Enabled = true;//edit
            Check_download_Timer.Enabled = true;
            DD_Interval_select.DropDownStyle = ComboBoxStyle.DropDownList;
            
        }

     

        //private void show_default_images(string path)
        //{
        //    Image imgtemp = Image.FromFile(path);
        //    PB_display_pic.Width = imgtemp.Width;
        //    PB_display_pic.Height = imgtemp.Height;
        //    PB_display_pic.Image = imgtemp;
        //}


        //private void nextImage()
        //{
        //    if (m_selected == m_local_images.Length - 1)
        //    {
        //        m_selected = 0;
        //        show_default_images(m_local_images[m_selected]);
        //    }
        //    else
        //    {
        //        m_selected = m_selected + 1; 
        //        show_default_images(m_local_images[m_selected]);
        //    }
        //}

        private void DB_Start_Stop_Click(object sender, System.EventArgs e)
        {
            if (Picture_Display_Timer.Enabled == true)
            {
                Picture_Display_Timer.Enabled = false;
                DB_Start_Stop.Text = "START";
            }
            else
            {
                Picture_Display_Timer.Enabled = true;
                DB_Start_Stop.Text = "STOP";
            }
        }

        private void Picture_Display_Timer_Tick(object sender, EventArgs e)
        {
            next();
        }

        private void DB_Set_Interval_Click(object sender, EventArgs e)
        {
            Picture_Display_Timer.Interval = Convert.ToInt32(DD_Interval_select.Text)*1000;
            m_download_num = (int)(30 / Convert.ToInt32(DD_Interval_select.Text));
            RT_Inf_display.Text = "Display interval time is " + DD_Interval_select.Text + " second(s)"+ RT_Inf_display.Text;
            RT_Inf_display.Text = "Next time will download " + m_download_num + " pictures \n" + RT_Inf_display.Text;
        }
        //connect to database
        public bool connnect_sql()
        {
            //connection string
            String constr = "Data Source=SQL01;Initial Catalog=SuperSign;User ID=sa;Password=sa";
            //String constr = "Data Source=BBDB;Initial Catalog=ABC_Schedule;Persist Security Info=True;User ID=sa;Password=gopowerbar";
            SqlConnection conn = new SqlConnection(constr);
            try
            {
                conn.Open();


                //String sql = "select [DateTime] from dbo.ASSETSCHEDLOG where AssetID='4871' and DateTime>='2012-01-01 23:59:00' ";
                String sql = "select [DateTime] from dbo.ASSETSCHEDLOG where AssetID='" + m_assetID + "' and DateTime>='" + DateTime.Now.ToLocalTime().ToString()
                                    + "' and DateTime <='" + DateTime.Now.AddMinutes(33).ToString() + "'";//should add 33 min
                //MessageBox.Show(DateTime.Now.ToLocalTime().ToString());
                SqlDataAdapter find = new SqlDataAdapter(sql, conn);
                //MessageBox.Show("Connect success！");
                DataSet save = new DataSet();
                find.Fill(save);
                if (save != null)
                {
                    foreach (DataRow row in save.Tables[0].Rows)
                    {
                        //check if is already in the m_schedule
                        DateTime temp = Convert.ToDateTime(row["DateTime"]);

                        if (m_schedules.Contains(temp) != true)//not exist in m_schedules
                            m_schedules.Add(temp);
                    }
                    for (int i = 0; i < m_schedules.Count; i++)
                        RT_Inf_display.Text = m_schedules.ElementAt(i).ToString() + "\n" + RT_Inf_display.Text;
                }

                conn.Close();
            }
            catch (Exception e)
            {
                RT_Inf_display.Text = "can not connect to database , please check your network \n" + RT_Inf_display.Text;
                return false;
            }
            finally
            {
                if (m_schedules.Count == 0)//no schedule conntinue check the time to access database
                    Access_DB_Timer.Enabled = true;
                else
                {
                    Check_download_Timer.Enabled = true;
                }
            }
            return true;
        }
        
        //url
        private void next()//edit
        {
            //if (!m_is_default)
            //{
                if (m_selected_url == m_images.Length - 1)
                {
                    m_selected_url = 0;
                    show_images(m_images[m_selected_url]);
                }
                else
                {
                    m_selected_url = m_selected_url + 1;
                    show_images(m_images[m_selected_url]);
                }
            //}
            //else
            //{
            //    if (m_selected_url == m_images.Length - 1)
            //    {
            //        m_selected_url = 0;
            //        show_images(m_images_default[m_selected_url]);
            //    }
            //    else
            //    {
            //        m_selected_url = m_selected_url + 1;
            //        show_images(m_images_default[m_selected_url]);
            //    }
            //}
            
        }
        //url
        private void show_images(Image image)
        {
            PB_display_pic.Image = image;
        }
        //url
        private void button8_Click(object sender, EventArgs e)
        {
            next();
        }
        
        //timer for access database
        private void Access_DB_Timer_Tick(object sender, EventArgs e)
        {
            if (((DateTime.Now.Minute >= 27) && (DateTime.Now.Minute <= 28))
                || (DateTime.Now.Minute >= 57) && (DateTime.Now.Minute <= 58))
            {
                Access_DB_Timer.Enabled = false;//should be false when load pic
                //connnect_sql();//get schedule    
                if (!connnect_sql())//edit
                    Firsrt_start_timer.Enabled = true;//edit
            }
        }

        private void Check_Schedule_Timer_Tick(object sender, EventArgs e)
        {
            if (m_schedules.Count != 0)//edit
            {
                //compare to schedule
                DateTime pre_date = m_schedules.ElementAt(0); //schedule
                DateTime post_date = m_schedules.ElementAt(0).AddMilliseconds(500);
                int compare_pre_date = DateTime.Now.CompareTo(pre_date);//compare to time now
                int compare_post_date = DateTime.Now.CompareTo(post_date);//compare to time now
                if (compare_pre_date >= 0 && compare_post_date <= 0)//make sure the DateTime is almost the right time
                {
                    Check_Schedule_Timer.Enabled = false;//timer for check when to display
                    if (m_download_ready)
                    {
                        m_selected_url = 0;
                        Picture_Display_Timer.Enabled = true;//timer for display pic
                        Access_DB_Timer.Enabled = true;//timer for access database
                        show_images(m_images[m_selected_url]);
                        //DD_Interval_select.Text = Picture_Display_Timer.Interval.ToString();//does not work
                        //MessageBox.Show(Picture_Display_Timer.Interval.ToString());
                        DD_Interval_select.SelectedIndex = (int)(Picture_Display_Timer.Interval / 1000) - 1;
                        m_download_ready = false;
                    }
                    else if ((m_images_default != null))
                    {//will never reach here
                        //MessageBox.Show("no picture");
                        //display default images
                        m_selected_url = 0;
                        Picture_Display_Timer.Enabled = true;//timer for display pic
                        show_images(m_images[m_selected_url]);
                        DD_Interval_select.SelectedIndex = (int)(Picture_Display_Timer.Interval / 1000) - 1;
                        m_download_ready = false;

                    }
                    else
                    {
                    }
                    //MessageBox.Show("now: " + DateTime.Now.ToLocalTime().ToString());


                    m_schedules.Remove(m_schedules.ElementAt(0));
                    Check_download_Timer.Enabled = true;
                }
            }
            
            
            //if (DateTime.Now.CompareTo(DateTime).ToString)
            //{
            //    timer2.Enabled = false;//will be true after dsiplay
            //    connnect_sql();//get schedule    
            //}
            
        }

        //send request to wishoo
        private void button9_Click(object sender, EventArgs e)
        {
            request_wishoo();
            download_pic();
            //sw.Close();

        }
        //request to wishoo 
        private bool request_wishoo()
        {
            //int num = 30;
            try
            {

                String URLString = "http://a.wtx.me/customtour/abc_supersign_2013/rss.aspx?num=" + m_download_num;
                XmlTextReader reader = new XmlTextReader(URLString);
                // StreamWriter sw = new StreamWriter("D:/test.xml");
                bool default_image = false;//whether the image is default images
                m_ArrayImage_url.Clear();
                m_defaultArray_url.Clear();

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element: // The node is an element.
                            //RT_Inf_display.Text += reader.Name + ": \n";
                            if (reader.Name.Equals("Default"))
                                default_image = true;
                            if (reader.Name.Equals("IMG"))
                                default_image = false;
                            break;
                        case XmlNodeType.Text: //Display the text in each element.
                            //RT_Inf_display.Text += reader.Value + "\n";
                            if (default_image)
                                m_defaultArray_url.Add(reader.Value);
                            else
                                m_ArrayImage_url.Add(reader.Value);
                            break;
                    }
                }
                if (m_ArrayImage_url.Count > 0)
                {
                    m_num_pic = m_ArrayImage_url.Count;
                    return true;
                }
                else
                    return false;
            }
            catch (Exception w)//edit
            {
                RT_Inf_display.Text = "can not access to wishoo, please check your network \n" + RT_Inf_display.Text;
                //MessageBox.Show(w.ToString());
                return false;
            }
        }
        //download pic
        private void download_pic()
        {
            if (m_ArrayImage_url.Count != 0)
            {
                RT_Inf_display.Text = "start download picture\n" + RT_Inf_display.Text;
                int number = m_ArrayImage_url.Count;
                Image[] tmp_images = new Image[number];
                int image_acount = 0;
                try
                {
                    foreach (String url in m_ArrayImage_url)
                    {
                        var request = WebRequest.Create(url);
                        var response = request.GetResponse();
                        var stream = response.GetResponseStream();
                        tmp_images[image_acount] = Bitmap.FromStream(stream);
                        image_acount++;
                    }
                    m_images = new Image[tmp_images.Length];
                    Array.Copy(tmp_images, 0, m_images, 0, tmp_images.Length);
                    m_end = m_images.Length;
                    m_selected_url = 0;
                    show_images(m_images[m_selected_url]);
                    RT_Inf_display.Text = "Download " + m_ArrayImage_url.Count.ToString() + " pictures \n" + RT_Inf_display.Text;
                    Picture_Display_Timer.Interval = ((int)(30 / m_ArrayImage_url.Count)) * 1000;//should be 1000
                    m_download_ready = true;
                }
                catch (Exception e)//edit
                {
                    //m_is_default = true;
                    RT_Inf_display.Text = "can not download pictures, please check your network \n" + RT_Inf_display.Text;
                    m_download_ready = false;
                }  
            }
            //if (m_defaultArray_url.Count != 0)
            //{
            //    int number = m_defaultArray_url.Count;
            //    Image[] tmp_images = new Image[number];
            //    int image_acount = 0;
            //    try
            //    {
            //        foreach (String url in m_defaultArray_url)
            //        {
            //            var request = WebRequest.Create(url);
            //            var response = request.GetResponse();
            //            var stream = response.GetResponseStream();
            //            tmp_images[image_acount] = Bitmap.FromStream(stream);
            //            image_acount++;
            //        }

            //        m_images_default = new Image[tmp_images.Length];
            //        Array.Copy(tmp_images, 0, m_images_default, 0, tmp_images.Length);
            //        if (!m_download_ready)
            //        {
            //            m_end = m_images.Length;
            //            m_selected_url = 0;
            //            show_images(m_images_default[m_selected_url]);
            //            //m_is_default = true;
            //        }

            //        //MessageBox.Show(m_defaultArray_url.Count.ToString());
            //    }
            //    catch (Exception e)
            //    {
            //    } 
            //}
            
            
        }

        //when to download pic
        private void Check_download_Timer_Tick(object sender, EventArgs e)
        {
            if (m_schedules.Count != 0)
            {
                DateTime pre_date = m_schedules.ElementAt(0).AddSeconds(-25); //schedule
                DateTime post_date = m_schedules.ElementAt(0).AddSeconds(-20);//edit
                int compare_pre_date = DateTime.Now.CompareTo(pre_date);//compare to time now
                int compare_post_date = DateTime.Now.CompareTo(post_date);//compare to time now
                if (compare_pre_date >= 0 && compare_post_date <= 0)//make sure the DateTime is almost the right time
                {
                    if (request_wishoo())
                    {
                        //set display pic timer false
                        Picture_Display_Timer.Enabled = false;
                        Check_Schedule_Timer.Enabled = true;
                        Check_download_Timer.Enabled = false;
                        //MessageBox.Show("start download pictures");
                        download_pic();
                        //MessageBox.Show(Check_download_Timer.Enabled.ToString());
                    }
                    else
                    {
                        Picture_Display_Timer.Enabled = false;
                        Check_Schedule_Timer.Enabled = true;
                        Check_download_Timer.Enabled = false;
                    }
                }
                
            }
        }


        //just for test wishoo xml
        private void button10_Click(object sender, EventArgs e)
        {
            int count = 60;
            try
             {
                // Create an XML document instance and load the XML data.
                XmlDocument doc  = new XmlDocument();
                // This code assumes that the XML file is in the same folder.
                doc.Load("http://a.wtx.me/customtour/abc_supersign_2013/rss.aspx?count="+count);                      

                // Save the XML to a file.
                doc.Save("D:/test.xml");
             }
             catch(XmlException xmlEx) {
                Console.WriteLine("{0}", xmlEx.Message);
             }
         
        }

        //just for db connection test
        private void test_db_Click(object sender, EventArgs e)
        {
            connnect_sql();
        }

        private void RT_Inf_display_TextChanged(object sender, EventArgs e)
        {
            //RT_Inf_display.Clear();
            ////schedule is not empty
            //if(m_schedules.Count != 0)
            //{
            //    RT_Inf_display.Text += "The next display time: "+m_schedules.ElementAt(0)+"\n";
            //    for(int i = 0; i<m_schedules.Count; i++)
            //    {
            //        RT_Inf_display.Text += m_schedules.ElementAt(i) + "\n";
            //    }
            //}
            //RT_Inf_display.Text += "Already download "+ m_num_pic +" pictures \n";
            //RT_Inf_display.Text += "Next time will download " + m_download_num + " pictures \n";
            //RT_Inf_display.Text += "Display interval time is " + (int)(Picture_Display_Timer.Interval/1000)+" second \n";
        }

        private void First_start_timer_Tick(object sender, EventArgs e)
        {
            if (connnect_sql())
                Firsrt_start_timer.Enabled = false;         
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Picture_Display_Timer.Interval = Convert.ToInt32(DD_Interval_select.Text) * 1000;
            m_download_num = (int)(30 / Convert.ToInt32(DD_Interval_select.Text));
            RT_Inf_display.Text = "Display interval time is " + DD_Interval_select.Text + " second(s)" + RT_Inf_display.Text;
            RT_Inf_display.Text = "Next time will download " + m_download_num + " pictures \n" + RT_Inf_display.Text;
        }

      

        

        
    }
}
